<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\command\reportexcel;

use app\command\BaseWork;
use app\enum\ReportRecordEnum;
use app\model\report\ReportRecordListModel;
use app\service\report\ReportRecordListService;
use think\console\Input;
use think\console\Output;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Cache;

class ReportRecordSendProducerWork extends BaseWork
{
    protected function configure()
    {
        // 指令配置
        $this->setName('v3_report_record_send_producer_work');
        $this->setDescription('报表发送生产者');
    }

    /**
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);
        ini_set('memory_limit', '-1');
        $st = time() + 5 * 60;
        while (time() < $st) {
            $sendDate = intval(date('Ymd'));
            $items = ReportRecordListService::getListSendIds($sendDate);
            if (! $items) {
                usleep(500000);
                continue;
            }
            $redis = Cache::store('redis')->handler();
            $key = ReportRecordEnum::CACHE_KEY['report_send_list'];
            foreach ($items as $obj) {
                if (! $obj instanceof ReportRecordListModel && ! $obj->getKey()) {
                    $this->getOutputMessage('报表发送暂无数据');
                    continue;
                }
                try {
                    $redis->rPush($key, $obj->getKey());
                } catch (\Exception $e) {
                    $this->getOutputMessage('生成发送报表数据队列失败' . $e->getMessage());
                }
            }
        }
        $this->getOutputMessage('生成发送报表数据队列结束');
    }
}
